package com.lhz.executor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lhz.manager.JobManager;
import com.lhz.mapper.JobMapper;
import com.lhz.model.constant.RunnableConstant;
import com.lhz.model.entity.JobInfo;
import com.lhz.service.ExecutorService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: LiHuaZhi
 * @Date: 2024/03/11 15:38
 * @Description:
 **/

@Component
@Slf4j
public class JobCheckScheduled {

    @Resource
    private ExecutorService executorService;

    @Resource
    private JobMapper jobMapper;

    @Resource
    private JobManager jobManager;

    /**
     * 与数据库中进行中的任务进行比较
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    //@Scheduled(cron = "0/12 * * * * ?")
    public void checkJob() {
        log.info("任务对比进行中....");
        QueryWrapper<JobInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(JobInfo::getDelFlag, 1);
        List<JobInfo> jobInfoList = jobMapper.selectList(queryWrapper);
        // 数据库存在执行中的任务 ，但是服务器没有执行
        List<JobInfo> startJobList = jobInfoList.stream().filter(x -> x.getStatus() == 1 && x.getTriggerStatus() == 1).toList();
        for (JobInfo jobInfo : startJobList) {
            JobInfo job = RunnableConstant.JOB_MAP.get(jobInfo.getId());
            if (job == null) {
                jobManager.start(jobInfo);
            }
        }

        // 数据库任务已经终止，但是服务器还有任务
        List<JobInfo> stopJobList = jobInfoList.stream().filter(x -> x.getStatus() == 2 || x.getTriggerStatus() == 2).toList();
        for (JobInfo jobInfo : stopJobList) {
            JobInfo job = RunnableConstant.JOB_MAP.get(jobInfo.getId());
            if (job != null) {
                jobManager.close(job.getId(), job.getName());
            }
        }
        log.info("任务对比结束....");
    }

    /**
     * 集群中 其他机器健康检测
     */
    @Scheduled(cron = "0 0/30 * * * ?")
//    @Scheduled(cron = "0/12 * * * * ?")
    public void checkHealth() {
        executorService.healthJob();
    }
}
